package com.syt.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syt.common.utils.HttpUtils;
import com.syt.mall.member.dao.MemberLevelDao;
import com.syt.mall.member.entity.MemberLevelEntity;
import com.syt.mall.member.exception.PhoneExistException;
import com.syt.mall.member.exception.UsernameExistException;
import com.syt.mall.member.service.MemberLevelService;
import com.syt.mall.member.vo.MemberLoginVo;
import com.syt.mall.member.vo.MemberRegistVo;
import com.syt.mall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.lang.reflect.Member;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syt.common.utils.PageUtils;
import com.syt.common.utils.Query;

import com.syt.mall.member.dao.MemberDao;
import com.syt.mall.member.entity.MemberEntity;
import com.syt.mall.member.service.MemberService;

import javax.imageio.spi.RegisterableService;
import javax.swing.text.html.parser.Entity;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();
        MemberDao memberDao = this.baseMapper;
        //设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLave();
        entity.setLevelId(memberLevelEntity.getId());


        //检查用户名和手机号是否唯一,为了让controller能感知异常,异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUserName());
        //密码要进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        //替他的默认信息
        entity.setNickname(vo.getUserName());
        //保存
        memberDao.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao memberDao = this.baseMapper;
        Integer mo = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mo > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        MemberDao memberDao = this.baseMapper;
        Integer mo = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (mo > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        //1.去数据库查询
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberEntity == null) {
            //登录失败
            return null;
        } else {
            //获取到数据库Password
            String passwordDB = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDB);
            if (matches) {
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        //登录和注册合并逻辑
        String uid = socialUser.getUid();
        //1.判断当前社交用户是否已经登录过系统
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //这个用户已经注册了
            MemberEntity update = new MemberEntity();
            BeanUtils.copyProperties(memberEntity, update, MemberEntity.class);
            update.setAccessToken(socialUser.getAccessToken());
            update.setExpiressIn(socialUser.getExpiresIn());
            memberDao.updateById(update);
            return update;
        } else {
            //2.没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity regist = new MemberEntity();
            try {
                //3.查询当前社交用户的社交信息(昵称,性别等)
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccessToken());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //昵称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");
                    // ...
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender) ? 1 : 0);
                    // ...
                }
            }catch (Exception e){ }

            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccessToken());
            regist.setExpiressIn(socialUser.getExpiresIn());
            memberDao.insert(regist);
            return regist;
        }
    }

}